package com.eshop.utils.html;

import java.util.concurrent.ConcurrentHashMap;
import java.util.Iterator;
import java.util.regex.Matcher;
import java.util.Collections;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentMap;
import java.util.regex.Pattern;

public final class HTMLFilter
{
    private static final int REGEX_FLAGS_SI = 34;
    private static final Pattern P_COMMENTS;
    private static final Pattern P_COMMENT;
    private static final Pattern P_TAGS;
    private static final Pattern P_END_TAG;
    private static final Pattern P_START_TAG;
    private static final Pattern P_QUOTED_ATTRIBUTES;
    private static final Pattern P_UNQUOTED_ATTRIBUTES;
    private static final Pattern P_PROTOCOL;
    private static final Pattern P_ENTITY;
    private static final Pattern P_ENTITY_UNICODE;
    private static final Pattern P_ENCODE;
    private static final Pattern P_VALID_ENTITIES;
    private static final Pattern P_VALID_QUOTES;
    private static final Pattern P_END_ARROW;
    private static final Pattern P_XML_CONTENT;
    private static final Pattern P_STRAY_LEFT_ARROW;
    private static final Pattern P_STRAY_RIGHT_ARROW;
    private static final Pattern P_AMP;
    private static final Pattern P_QUOTE;
    private static final Pattern P_LEFT_ARROW;
    private static final Pattern P_RIGHT_ARROW;
    private static final Pattern P_BOTH_ARROWS;
    private static final ConcurrentMap<String, Pattern> P_REMOVE_PAIR_BLANKS;
    private static final ConcurrentMap<String, Pattern> P_REMOVE_SELF_BLANKS;
    private final Map<String, List<String>> vAllowed;
    private final Map<String, Integer> vTagCounts;
    private final String[] vSelfClosingTags;
    private final String[] vNeedClosingTags;
    private final String[] vDisallowed;
    private final String[] vProtocolAtts;
    private final String[] vAllowedProtocols;
    private final String[] vRemoveBlanks;
    private final String[] vAllowedEntities;
    private final boolean stripComment;
    private final boolean encodeQuotes;
    private final boolean alwaysMakeTags;
    
    public HTMLFilter() {
        this.vTagCounts = new HashMap<String, Integer>();
        this.vAllowed = new HashMap<String, List<String>>();
        final ArrayList<String> a_atts = new ArrayList<String>();
        a_atts.add("href");
        a_atts.add("target");
        this.vAllowed.put("a", a_atts);
        final ArrayList<String> img_atts = new ArrayList<String>();
        img_atts.add("src");
        img_atts.add("width");
        img_atts.add("height");
        img_atts.add("alt");
        this.vAllowed.put("img", img_atts);
        final ArrayList<String> no_atts = new ArrayList<String>();
        this.vAllowed.put("b", no_atts);
        this.vAllowed.put("strong", no_atts);
        this.vAllowed.put("i", no_atts);
        this.vAllowed.put("em", no_atts);
        this.vSelfClosingTags = new String[] { "img" };
        this.vNeedClosingTags = new String[] { "a", "b", "strong", "i", "em" };
        this.vDisallowed = new String[0];
        this.vAllowedProtocols = new String[] { "http", "mailto", "https" };
        this.vProtocolAtts = new String[] { "src", "href" };
        this.vRemoveBlanks = new String[] { "a", "b", "strong", "i", "em" };
        this.vAllowedEntities = new String[] { "amp", "gt", "lt", "quot" };
        this.stripComment = true;
        this.encodeQuotes = true;
        this.alwaysMakeTags = true;
    }
    
    public HTMLFilter(final Map<String, Object> conf) {
        this.vTagCounts = new HashMap<String, Integer>();
        assert conf.containsKey("vAllowed") : "configuration requires vAllowed";
        assert conf.containsKey("vSelfClosingTags") : "configuration requires vSelfClosingTags";
        assert conf.containsKey("vNeedClosingTags") : "configuration requires vNeedClosingTags";
        assert conf.containsKey("vDisallowed") : "configuration requires vDisallowed";
        assert conf.containsKey("vAllowedProtocols") : "configuration requires vAllowedProtocols";
        assert conf.containsKey("vProtocolAtts") : "configuration requires vProtocolAtts";
        assert conf.containsKey("vRemoveBlanks") : "configuration requires vRemoveBlanks";
        assert conf.containsKey("vAllowedEntities") : "configuration requires vAllowedEntities";
        this.vAllowed = Collections.unmodifiableMap((Map<? extends String, ? extends List<String>>)conf.get("vAllowed"));
        this.vSelfClosingTags = (String[]) conf.get("vSelfClosingTags");
        this.vNeedClosingTags = (String[]) conf.get("vNeedClosingTags");
        this.vDisallowed = (String[]) conf.get("vDisallowed");
        this.vAllowedProtocols = (String[]) conf.get("vAllowedProtocols");
        this.vProtocolAtts = (String[]) conf.get("vProtocolAtts");
        this.vRemoveBlanks = (String[]) conf.get("vRemoveBlanks");
        this.vAllowedEntities = (String[]) conf.get("vAllowedEntities");
        this.stripComment = (!conf.containsKey("stripComment") || (boolean)conf.get("stripComment"));
        this.encodeQuotes = (!conf.containsKey("encodeQuotes") ||  (boolean)conf.get("encodeQuotes"));
        this.alwaysMakeTags = (!conf.containsKey("alwaysMakeTags") ||  (boolean) conf.get("alwaysMakeTags"));
    }
    
    private void reset() {
        this.vTagCounts.clear();
    }
    
    public static String chr(final int decimal) {
        return String.valueOf((char)decimal);
    }
    
    public static String htmlSpecialChars(final String s) {
        String result = s;
        result = regexReplace(HTMLFilter.P_AMP, "&amp;", result);
        result = regexReplace(HTMLFilter.P_QUOTE, "&quot;", result);
        result = regexReplace(HTMLFilter.P_LEFT_ARROW, "&lt;", result);
        result = regexReplace(HTMLFilter.P_RIGHT_ARROW, "&gt;", result);
        return result;
    }
    
    public String filter(final String input) {
        this.reset();
        String s = input;
        s = this.escapeComments(s);
        s = this.balanceHTML(s);
        s = this.checkTags(s);
        s = this.processRemoveBlanks(s);
        s = this.validateEntities(s);
        return s;
    }
    
    public boolean isAlwaysMakeTags() {
        return this.alwaysMakeTags;
    }
    
    public boolean isStripComments() {
        return this.stripComment;
    }
    
    private String escapeComments(final String s) {
        final Matcher m = HTMLFilter.P_COMMENTS.matcher(s);
        final StringBuffer buf = new StringBuffer();
        if (m.find()) {
            final String match = m.group(1);
            m.appendReplacement(buf, Matcher.quoteReplacement("<!--" + htmlSpecialChars(match) + "-->"));
        }
        m.appendTail(buf);
        return buf.toString();
    }
    
    private String balanceHTML(String s) {
        if (this.alwaysMakeTags) {
            s = regexReplace(HTMLFilter.P_END_ARROW, "", s);
            s = regexReplace(HTMLFilter.P_XML_CONTENT, "$1<$2", s);
        }
        else {
            s = regexReplace(HTMLFilter.P_STRAY_LEFT_ARROW, "&lt;$1", s);
            s = regexReplace(HTMLFilter.P_STRAY_RIGHT_ARROW, "$1$2&gt;<", s);
            s = regexReplace(HTMLFilter.P_BOTH_ARROWS, "", s);
        }
        return s;
    }
    
    private String checkTags(String s) {
        final Matcher m = HTMLFilter.P_TAGS.matcher(s);
        final StringBuffer buf = new StringBuffer();
        while (m.find()) {
            String replaceStr = m.group(1);
            replaceStr = this.processTag(replaceStr);
            m.appendReplacement(buf, Matcher.quoteReplacement(replaceStr));
        }
        m.appendTail(buf);
        final StringBuilder sBuilder = new StringBuilder(buf.toString());
        for (final String key : this.vTagCounts.keySet()) {
            for (int ii = 0; ii < this.vTagCounts.get(key); ++ii) {
                sBuilder.append("</").append(key).append(">");
            }
        }
        s = sBuilder.toString();
        return s;
    }
    
    private String processRemoveBlanks(final String s) {
        String result = s;
        for (final String tag : this.vRemoveBlanks) {
            if (!HTMLFilter.P_REMOVE_PAIR_BLANKS.containsKey(tag)) {
                HTMLFilter.P_REMOVE_PAIR_BLANKS.putIfAbsent(tag, Pattern.compile("<" + tag + "(\\s[^>]*)?></" + tag + ">"));
            }
            result = regexReplace(HTMLFilter.P_REMOVE_PAIR_BLANKS.get(tag), "", result);
            if (!HTMLFilter.P_REMOVE_SELF_BLANKS.containsKey(tag)) {
                HTMLFilter.P_REMOVE_SELF_BLANKS.putIfAbsent(tag, Pattern.compile("<" + tag + "(\\s[^>]*)?/>"));
            }
            result = regexReplace(HTMLFilter.P_REMOVE_SELF_BLANKS.get(tag), "", result);
        }
        return result;
    }
    
    private static String regexReplace(final Pattern regex_pattern, final String replacement, final String s) {
        final Matcher m = regex_pattern.matcher(s);
        return m.replaceAll(replacement);
    }
    
    private String processTag(final String s) {
        Matcher m = HTMLFilter.P_END_TAG.matcher(s);
        if (m.find()) {
            final String name = m.group(1).toLowerCase();
            if (this.allowed(name) && !inArray(name, this.vSelfClosingTags) && this.vTagCounts.containsKey(name)) {
                this.vTagCounts.put(name, this.vTagCounts.get(name) - 1);
                return "</" + name + ">";
            }
        }
        m = HTMLFilter.P_START_TAG.matcher(s);
        if (m.find()) {
            final String name = m.group(1).toLowerCase();
            final String body = m.group(2);
            String ending = m.group(3);
            if (this.allowed(name)) {
                final StringBuilder params = new StringBuilder();
                final Matcher m2 = HTMLFilter.P_QUOTED_ATTRIBUTES.matcher(body);
                final Matcher m3 = HTMLFilter.P_UNQUOTED_ATTRIBUTES.matcher(body);
                final List<String> paramNames = new ArrayList<String>();
                final List<String> paramValues = new ArrayList<String>();
                while (m2.find()) {
                    paramNames.add(m2.group(1));
                    paramValues.add(m2.group(3));
                }
                while (m3.find()) {
                    paramNames.add(m3.group(1));
                    paramValues.add(m3.group(3));
                }
                for (int ii = 0; ii < paramNames.size(); ++ii) {
                    final String paramName = paramNames.get(ii).toLowerCase();
                    String paramValue = paramValues.get(ii);
                    if (this.allowedAttribute(name, paramName)) {
                        if (inArray(paramName, this.vProtocolAtts)) {
                            paramValue = this.processParamProtocol(paramValue);
                        }
                        params.append(' ').append(paramName).append("=\"").append(paramValue).append("\"");
                    }
                }
                if (inArray(name, this.vSelfClosingTags)) {
                    ending = " /";
                }
                if (inArray(name, this.vNeedClosingTags)) {
                    ending = "";
                }
                if (ending == null || ending.length() < 1) {
                    if (this.vTagCounts.containsKey(name)) {
                        this.vTagCounts.put(name, this.vTagCounts.get(name) + 1);
                    }
                    else {
                        this.vTagCounts.put(name, 1);
                    }
                }
                else {
                    ending = " /";
                }
                return "<" + name + (Object)params + ending + ">";
            }
            return "";
        }
        else {
            m = HTMLFilter.P_COMMENT.matcher(s);
            if (!this.stripComment && m.find()) {
                return "<" + m.group() + ">";
            }
            return "";
        }
    }
    
    private String processParamProtocol(String s) {
        s = this.decodeEntities(s);
        final Matcher m = HTMLFilter.P_PROTOCOL.matcher(s);
        if (m.find()) {
            final String protocol = m.group(1);
            if (!inArray(protocol, this.vAllowedProtocols)) {
                s = "#" + s.substring(protocol.length() + 1);
                if (s.startsWith("#//")) {
                    s = "#" + s.substring(3);
                }
            }
        }
        return s;
    }
    
    private String decodeEntities(String s) {
        StringBuffer buf = new StringBuffer();
        Matcher m = HTMLFilter.P_ENTITY.matcher(s);
        while (m.find()) {
            final String match = m.group(1);
            final int decimal = Integer.decode(match);
            m.appendReplacement(buf, Matcher.quoteReplacement(chr(decimal)));
        }
        m.appendTail(buf);
        s = buf.toString();
        buf = new StringBuffer();
        m = HTMLFilter.P_ENTITY_UNICODE.matcher(s);
        while (m.find()) {
            final String match = m.group(1);
            final int decimal = Integer.valueOf(match, 16);
            m.appendReplacement(buf, Matcher.quoteReplacement(chr(decimal)));
        }
        m.appendTail(buf);
        s = buf.toString();
        buf = new StringBuffer();
        m = HTMLFilter.P_ENCODE.matcher(s);
        while (m.find()) {
            final String match = m.group(1);
            final int decimal = Integer.valueOf(match, 16);
            m.appendReplacement(buf, Matcher.quoteReplacement(chr(decimal)));
        }
        m.appendTail(buf);
        s = buf.toString();
        s = this.validateEntities(s);
        return s;
    }
    
    private String validateEntities(final String s) {
        final StringBuffer buf = new StringBuffer();
        final Matcher m = HTMLFilter.P_VALID_ENTITIES.matcher(s);
        while (m.find()) {
            final String one = m.group(1);
            final String two = m.group(2);
            m.appendReplacement(buf, Matcher.quoteReplacement(this.checkEntity(one, two)));
        }
        m.appendTail(buf);
        return this.encodeQuotes(buf.toString());
    }
    
    private String encodeQuotes(final String s) {
        if (this.encodeQuotes) {
            final StringBuffer buf = new StringBuffer();
            final Matcher m = HTMLFilter.P_VALID_QUOTES.matcher(s);
            while (m.find()) {
                final String one = m.group(1);
                final String two = m.group(2);
                final String three = m.group(3);
                m.appendReplacement(buf, Matcher.quoteReplacement(one + two + three));
            }
            m.appendTail(buf);
            return buf.toString();
        }
        return s;
    }
    
    private String checkEntity(final String preamble, final String term) {
        return (";".equals(term) && this.isValidEntity(preamble)) ? ('&' + preamble) : ("&amp;" + preamble);
    }
    
    private boolean isValidEntity(final String entity) {
        return inArray(entity, this.vAllowedEntities);
    }
    
    private static boolean inArray(final String s, final String[] array) {
        for (final String item : array) {
            if (item != null && item.equals(s)) {
                return true;
            }
        }
        return false;
    }
    
    private boolean allowed(final String name) {
        return (this.vAllowed.isEmpty() || this.vAllowed.containsKey(name)) && !inArray(name, this.vDisallowed);
    }
    
    private boolean allowedAttribute(final String name, final String paramName) {
        return this.allowed(name) && (this.vAllowed.isEmpty() || this.vAllowed.get(name).contains(paramName));
    }
    
    static {
        P_COMMENTS = Pattern.compile("<!--(.*?)-->", 32);
        P_COMMENT = Pattern.compile("^!--(.*)--$", 34);
        P_TAGS = Pattern.compile("<(.*?)>", 32);
        P_END_TAG = Pattern.compile("^/([a-z0-9]+)", 34);
        P_START_TAG = Pattern.compile("^([a-z0-9]+)(.*?)(/?)$", 34);
        P_QUOTED_ATTRIBUTES = Pattern.compile("([a-z0-9]+)=([\"'])(.*?)\\2", 34);
        P_UNQUOTED_ATTRIBUTES = Pattern.compile("([a-z0-9]+)(=)([^\"\\s']+)", 34);
        P_PROTOCOL = Pattern.compile("^([^:]+):", 34);
        P_ENTITY = Pattern.compile("&#(\\d+);?");
        P_ENTITY_UNICODE = Pattern.compile("&#x([0-9a-f]+);?");
        P_ENCODE = Pattern.compile("%([0-9a-f]{2});?");
        P_VALID_ENTITIES = Pattern.compile("&([^&;]*)(?=(;|&|$))");
        P_VALID_QUOTES = Pattern.compile("(>|^)([^<]+?)(<|$)", 32);
        P_END_ARROW = Pattern.compile("^>");
        P_XML_CONTENT = Pattern.compile("(^|>)([^<]*?)(?=>)");
        P_STRAY_LEFT_ARROW = Pattern.compile("<([^>]*?)(?=<|$)");
        P_STRAY_RIGHT_ARROW = Pattern.compile("(^|>)([^<]*?)(?=>)");
        P_AMP = Pattern.compile("&");
        P_QUOTE = Pattern.compile("\"");
        P_LEFT_ARROW = Pattern.compile("<");
        P_RIGHT_ARROW = Pattern.compile(">");
        P_BOTH_ARROWS = Pattern.compile("<>");
        P_REMOVE_PAIR_BLANKS = new ConcurrentHashMap<String, Pattern>();
        P_REMOVE_SELF_BLANKS = new ConcurrentHashMap<String, Pattern>();
    }
}
